package com.amos.server.mq;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.nio.charset.StandardCharsets;

/**
 * PROJECT: config-server
 * DESCRIPTION: note
 *
 * @author Daoyuan
 * @date 2019/3/1
 */
public class RabbitServer {

    private final static String QUEUE_NAME = "hello";

    public static void main(String[] argv) throws Exception {
        // 创建连接工厂 || 设置RabbitMQ地址
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        // 创建一个新的连接 || 创建一个频道
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        // 声明一个队列 || 发送消息到队列中
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        for (int i = 0; i < 10; i++) {
            MessageDTO<String> messageDTO = new MessageDTO<>();
            messageDTO.setId("ID_" + i);
            messageDTO.setTag("PRO_LOGIN");
            messageDTO.setBody("Hello World! " + i);

            channel.basicPublish("", QUEUE_NAME, null, JSON.toJSONString(messageDTO).getBytes(StandardCharsets.UTF_8));
            System.out.println("P [" + messageDTO.getId() + "] Sent [" + messageDTO.getBody() + "]");
        }
        // 关闭频道和连接
        channel.close();
        connection.close();
    }

}
